package com.baosight.risk.common.utils;

import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import com.baosight.risk.web.shiro.ShiroDbRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;

/**
 * shiro 工具类
 *
 * @author duanyongqiang
 */
public class ShiroUtils {
    public static Subject getSubjct() {
        return SecurityUtils.getSubject();
    }

    public static void logout() {
        getSubjct().logout();
    }

    public static XtzyUser getUser() {
        XtzyUser user = new XtzyUser();
        Object obj = getSubjct().getPrincipal();
        if (StringUtils.isNotNull(obj)) {
            BeanUtils.copyBeanProp(user, obj);
        }
        return user;
    }

    public static void setUser(XtzyUser user) {
        Subject subject = getSubjct();
        PrincipalCollection principalCollection = subject.getPrincipals();
        String realmName = principalCollection.getRealmNames().iterator().next();   
        PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName);
        // 重新加载Principal
        subject.runAs(newPrincipalCollection);
    }

    public static void clearCachedAuthorizationInfo() {
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        ShiroDbRealm realm = (ShiroDbRealm) rsm.getRealms().iterator().next();
        realm.clearCachedAuthorizationInfo();
    }

    public static String getUserId() {
        return getUser().getId();
    }

    public static String getLoginName() {
        return getUser().getUserCode();
    }

}
